package com.lottery.ruok.lottrey.ui.widget;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.http.SslError;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.AddFriendsChannelDialogAcrivity;
import com.lottery.ruok.lottrey.activity.UserRecommendActivity;
import com.lottery.ruok.lottrey.ext.GlideExt;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.ActivityListRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.ActivityWeChatQQRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.ActivityListResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.ActivityWeChatQQResponse;
import com.lottery.ruok.lottrey.ui.component.BaseRelativeLayout;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.lottery.ruok.lottrey.utils.DisplayUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import utils.Utils;

//活动详情View
public class ActivityInfoItem extends BaseRelativeLayout {
    @BindView(R.id.activity_name)
    TextView activityName;
    @BindView(R.id.missions_title)
    TextView missionsTitle;
    @BindView(R.id.btn_refresh)
    ImageButton btnRefresh;

    @BindView(R.id.ll_container)
    LinearLayout llContainer;
    @BindView(R.id.activities_container)
    HorizontalScrollView activitiesContainer;
    @BindView(R.id.activities_info)
    WebView activitiesInfo;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.iv_right_status)
    ImageView ivRightStatus;
    @BindView(R.id.btn_explanation1)
    ImageButton btnExplanation1;
    @BindView(R.id.btn_explanation2)
    ImageButton btnExplanation2;
    @BindView(R.id.rl_progress_container)
    RelativeLayout mProgressContainer;
    //    @BindView(R.id.left_icon)
//    ImageView leftIcon;
    @BindView(R.id.tv_subheading)
    TextView tvSubheading;
    @BindView(R.id.iv_item_info_top)
    ImageView ivItemInfoTop;
    @BindView(R.id.rl_activity_item)
    RelativeLayout rlActivityItem;
    @BindView(R.id.rl_web_bg)
    RelativeLayout rlWebBg;
    @BindView(R.id.progress_title)
    RelativeLayout progressTitle;
    @BindView(R.id.progress_container)
    LinearLayout progressContainer;
    private ActivityListResponse.ListBean mData;
    private ActivityWeChatQQResponse mActivityWeChatQQResponses;
    private String mMissionId;

    public ActivityInfoItem(Context context) {
        super(context);
    }

    public ActivityInfoItem(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ActivityInfoItem(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void init(Context context, AttributeSet attrs, int defStyleAttr) {

    }

    @Override
    protected void initView(Context context) {
        setContentView(R.layout.activitiyinfo_item_layout);
    }

    @Override
    protected void load(Context context) {
    }

    @OnClick({R.id.btn_refresh, R.id.btn_explanation1, R.id.btn_explanation2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_refresh:
                refreshData();
                break;
            case R.id.btn_explanation1:
                jumpToShare();
                break;
            case R.id.btn_explanation2:
                openAddContactInformation();
                break;
        }
    }

    /**
     * 跳转至分享
     */
    private void jumpToShare() {
        ActivityWeChatQQResponse.ListBean help = mActivityWeChatQQResponses.getList().get(0);
        Intent intent = new Intent(mContext, UserRecommendActivity.class);
        intent.putExtra("recommendNums", help.getHelp());
        intent.putExtra("mRecommendUrl", help.getRecommend_url());
        mContext.startActivity(intent);
    }

    /**
     * 打开添加QQ好友或者微信
     */
    private void openAddContactInformation() {
        Intent intent = new Intent(mContext, AddFriendsChannelDialogAcrivity.class);
        intent.putExtra("data", mActivityWeChatQQResponses.getList().get(0));
        intent.putExtra("mission_id", mMissionId);
        mContext.startActivity(intent);
    }

    //获取任务帮助
    private void getMissionHelp() {
        btnExplanation1.setVisibility(GONE);
        btnExplanation2.setVisibility(GONE);

        for (ActivityListResponse.ListBean.MissionsBean missionsBean : mData.getMissions()) {
            if (missionsBean.getStatus() == 1) {
                mMissionId = missionsBean.getId() + "";
            }
        }
        if (mMissionId != null) {
            RetrofitBase.getRetrofit().create(ActivityWeChatQQRequest.class).getResult(UserInfo.getToken(), mMissionId)
                    .compose(RxHelper.<ActivityWeChatQQResponse>handleResult())
                    .subscribe(new RxSubscribe<ActivityWeChatQQResponse>(getContext()) {
                        @Override
                        protected void _onNext(ActivityWeChatQQResponse activityWeChatQQResponses) {
                            mActivityWeChatQQResponses = activityWeChatQQResponses;
                            initHelp();
                        }

                        @Override
                        protected boolean showDialog() {
                            return false;
                        }
                    });
        }
    }

    /**
     * 初始化帮助
     */
    private void initHelp() {
        List<ActivityWeChatQQResponse.ListBean> list = mActivityWeChatQQResponses.getList();
        if (list.size() == 0) {
            btnExplanation1.setVisibility(GONE);
            btnExplanation2.setVisibility(GONE);
            return;
        } else {
            ActivityWeChatQQResponse.ListBean listBean = list.get(0);
            //邀请为空隐藏
            if (!Utils.isEmpty(listBean.getRecommend_url())) {
                btnExplanation1.setVisibility(VISIBLE);
            }
            if (listBean.getInputs().size() != 0) {
                btnExplanation2.setVisibility(VISIBLE);
            }

        }

    }

    //刷新当前页面
    public void refreshData() {
        RetrofitBase.getRetrofit().create(ActivityListRequest.class)
                .getResult(UserInfo.getToken(), String.valueOf(mData.getId()), null)
                .compose(RxHelper.<ActivityListResponse>handleResult())
                .subscribe(new RxSubscribe<ActivityListResponse>(mContext) {
                    @Override
                    protected void _onNext(ActivityListResponse activityListResponse) {
                        setData(activityListResponse.getList().get(0));
                    }

                    @Override
                    protected boolean showDialog() {
                        return true;
                    }
                });
    }

    public void setData(ActivityListResponse.ListBean data) {
        if (data == null) {
            return;
        }
        this.mData = data;
        if (data.getStatus() == 2) {
            getMissionHelp();
        }
        if (!Utils.isEmpty(mData.getSubheading()) && !Utils.isEmpty(mData.getToast())) {
            tvSubheading.setText(mData.getToast() + ";" + mData.getSubheading());
        } else if (!Utils.isEmpty(mData.getSubheading())) {
            tvSubheading.setText(mData.getSubheading());
        } else if (!Utils.isEmpty(mData.getToast())) {
            tvSubheading.setText(mData.getToast());
        } else {
            tvSubheading.setVisibility(GONE);
        }
        //获取是否有可以领奖
//        leftIcon.setVisibility(View.GONE);
        boolean isReceive = false;
        for (ActivityListResponse.ListBean.MissionsBean missionsBean : mData.getMissions()) {
            if (missionsBean.getStatus() == 3) {
                isReceive = true;
            }
        }
//        if (isReceive) {
//            leftIcon.setBackgroundResource(R.mipmap.left_icon);
//            leftIcon.setVisibility(View.VISIBLE);
//        } else {
//            ArrayList<ActivityListResponse.ListBean.MissionsBean> missionsBeans1 = new ArrayList<>();
//            ArrayList<ActivityListResponse.ListBean.MissionsBean> missionsBeans2 = mData.getMissions();
//            for (ActivityListResponse.ListBean.MissionsBean missionsBean : missionsBeans2) {
//                if (missionsBean.getStatus() == 4) {
//                    missionsBeans1.add(missionsBean);
//                }
//            }
//            if (missionsBeans1.size() == missionsBeans2.size()) {
//                leftIcon.setBackgroundResource(R.mipmap.yilingwantupian);
//                leftIcon.setVisibility(View.VISIBLE);
//            }
//        }

        // 启用js
        activitiesInfo.getSettings().setJavaScriptEnabled(true);
        activitiesInfo.getSettings().setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            activitiesInfo.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //隐藏没参加的活动进度
        if (mData.getJoined() == 0) {
            progressContainer.setVisibility(GONE);
            progressTitle.setVisibility(GONE);
        }
        // 解决图片不显示
        activitiesInfo.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();//接受所有网站的证书
            }
        });
        activitiesInfo.loadData(getHtml(data.getRules()), "text/html; charset=UTF-8", null);
        //  activityName.setText(data.getName());

        //设置missionsTitle
        missionsTitle.setText("");
        for (ActivityListResponse.ListBean.MissionsBean missionsBean : data.getMissions()) {
            if (missionsBean.getStatus() == 1) {
                missionsTitle.setText(missionsBean.getTitle().getValue());
            }
        }
        String sMissionsTitle = missionsTitle.getText().toString().trim();

        if (Utils.isEmpty(sMissionsTitle)) {
            if (!isReceive) {
                ArrayList<ActivityListResponse.ListBean.MissionsBean> missionsBeans1 = new ArrayList<>();
                ArrayList<ActivityListResponse.ListBean.MissionsBean> missionsBeans2 = mData.getMissions();
                for (ActivityListResponse.ListBean.MissionsBean missionsBean : missionsBeans2) {
                    if (missionsBean.getStatus() == 4) {
                        missionsBeans1.add(missionsBean);
                    }
                }
                if (missionsBeans1.size() == missionsBeans2.size()) {
                    missionsTitle.setText(R.string.draw_complete);
                }
            } else {
                missionsTitle.setText(R.string.unclaimed);
            }
        }
        llContainer.removeAllViews();
        if (data.getMissions().size() == 1) {
            ActivitiesSingleMissions activitiesSingleMissions = new ActivitiesSingleMissions(mContext);
            activitiesSingleMissions.setData(mData.getMissions().get(0), mData.getId() + "", data.getStatus());
            activitiesSingleMissions.setHideMissionsTitle();
            llContainer.addView(activitiesSingleMissions);
        } else {
            int firstProcessing = 1;
            for (int i = 0; i < data.getMissions().size(); i++) {
                ActivityListResponse.ListBean.MissionsBean missionsBean = data.getMissions().get(i);
                if (missionsBean.getStatus() == 1 && firstProcessing == 1) {//这段代码主要是为了只让任务有发光效果，阶段奖励和终极大奖不发光
                    firstProcessing = -1;
                } else if (missionsBean.getStatus() == 1 && firstProcessing == -1) {
                    missionsBean.setStatus(0);
                }
                ActivitiesItemView activitiesItemView = new ActivitiesItemView(mContext);
                activitiesItemView.setData(data.getMissions(), missionsBean, mData.getId() + "", data.getStatus(), i);
                llContainer.addView(activitiesItemView);
                if (!(missionsBean.getStatus() == 1 && data.getStatus() == 2)) {
                   /* TextView activitiesContent = activitiesItemView.findViewById(R.id.activities_content);
                    LayoutParams lp = (LayoutParams) activitiesContent.getLayoutParams();
                    lp.leftMargin = (int) DisplayUtil.dip2px(38, mContext);
                    activitiesContent.setLayoutParams(lp);*/
                    LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) activitiesItemView.getLayoutParams();
                    lp.topMargin = (int) DisplayUtil.dip2px(5f, mContext);
                    activitiesItemView.setLayoutParams(lp);
                }
            }
        }
        tvTime.setText("·活动期间：" + (data.getStart_time()).substring(0, 16) + "至" + (data.getEnd_time()).substring(0, 16));
        switch (data.getStatus()) {
            case 1:
                ivRightStatus.setVisibility(INVISIBLE);
                btnRefresh.setVisibility(VISIBLE);
                break;
            case 2:
                ivRightStatus.setVisibility(INVISIBLE);
                btnRefresh.setVisibility(VISIBLE);
                break;
            case 3:
                ivRightStatus.setVisibility(VISIBLE);
                ivRightStatus.setBackgroundResource(R.mipmap.expired);
                btnExplanation1.setVisibility(INVISIBLE);
                btnExplanation2.setVisibility(INVISIBLE);
                btnRefresh.setVisibility(VISIBLE);
                break;
            case 4:
                ivRightStatus.setVisibility(VISIBLE);
                ivRightStatus.setBackgroundResource(R.mipmap.pause);
                btnExplanation1.setVisibility(INVISIBLE);
                btnExplanation2.setVisibility(INVISIBLE);
                btnRefresh.setVisibility(VISIBLE);
                break;
            case 102:
                ivRightStatus.setVisibility(INVISIBLE);
                btnExplanation1.setVisibility(INVISIBLE);
                btnExplanation2.setVisibility(INVISIBLE);
                btnRefresh.setVisibility(GONE);
                break;
        }
    }

    private String getHtml(String content) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>img{max-width: 100%; width:auto; height:auto!important;}</style>" +
                "</head>";
        return "<html>" + head + "<body>" + content + "</body></html>";

    }

    public void setTopImage(String uri) {
        GlideExt.setBackgroundDrawable(mContext, uri, ivItemInfoTop, R.mipmap.activities_top);
    }

    public void setTopbg(String color) {
        rlActivityItem.setBackgroundColor(Color.parseColor(color));
        rlWebBg.setBackgroundColor(Color.parseColor(color));
    }

}
